package de.hbrs.ooka.crs.servlet;

import de.hbrs.ooka.beans.UserBeanStatelessLocal;
import de.hbrs.ooka.beans.UserSessionStatefulLocal;
import de.hbrs.ooka.crs.servlet.constants.WebPageNames;
import de.hbrs.ooka.enums.Role;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AssignRightsServlet extends AbstractViewServlet {
    
    @EJB
    private UserBeanStatelessLocal userBean;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            
        UserSessionStatefulLocal crsBean = this.getCrsBean(request);

        RequestDispatcher rd = null;
        
        if(crsBean == null || !this.isUserAuthenticated(crsBean.getUser(), Role.ORGANIZER)){
            request.setAttribute("message", "Not logged in");
            request.setAttribute("redirect", WebPageNames.LoginViewPage);
            rd = request.getRequestDispatcher("/" + WebPageNames.ErrorPage + ".jsp");
            if(rd != null){
                rd.forward(request, response);
            }
        } else {
            String action = request.getParameter("action");
            
            if( action == null){
                request.setAttribute("name", crsBean.getUser().getName());
                request.setAttribute("userlist", this.userBean.getAllUsers());
                rd = request.getRequestDispatcher("/" + WebPageNames.AssignRightsPage + ".jsp");
                if(rd != null){
                    rd.forward(request, response);
                }
            } else if(action.equalsIgnoreCase("assignrightstouser")){
                String[] roles = request.getParameterValues("role");
                
                if(roles.length > 0 && request.getParameter("user") != null){
                    this.userBean.assignRights(request.getParameter("user"), roles);
                }
                
                request.setAttribute("userlist", this.userBean.getAllUsers());
                response.sendRedirect(WebPageNames.AssignRightsPage);
            }
        }
    }
}
